package com.distribute.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;

public class JsonUtils {

    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    private static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    static {
        OBJECT_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        OBJECT_MAPPER.setDateFormat(SIMPLE_DATE_FORMAT);
    }

    public static <T> T toBean(byte[] bytes,Class<T> clazz){
        try {
            return OBJECT_MAPPER.readValue(bytes,clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T toBean(String content,Class<T> clazz){
        try {
            return OBJECT_MAPPER.readValue(content,clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T toBean(Object object,Class<T> clazz){
        try {
            byte[] bytes = OBJECT_MAPPER.writeValueAsBytes(object);
            return OBJECT_MAPPER.readValue(bytes,clazz);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @param clazz
     * @param iClazz
     * @return
     * @param <O> 外层集合类型
     * @param <I> 内层集合类型
     */
    public static <O extends Collection,I> Collection<I> toList(String content,Class<O> clazz, Class<I> iClazz ){
        CollectionType javaType = OBJECT_MAPPER.getTypeFactory().constructCollectionType(clazz, iClazz);
        try {
            return OBJECT_MAPPER.readValue(content, javaType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T toList(String content, TypeReference<T> typeReference){
        try {
            return OBJECT_MAPPER.readValue(content, typeReference);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    public static String converString(Object body){
        try {
            return OBJECT_MAPPER.writeValueAsString(body);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

}
